package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.config.minio.config.MinioConfiguration;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.config.minio.properties.MinioProperties;
import com.atguigu.gmall.product.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author lhh
 * @ClassName FileServiceImpl
 * @date 2022 2022/12/1
 */

@Service
public class FileServiceImpl implements FileService {

    @Resource
    MinioProperties minioProperties;

    @Resource
    MinioClient minioClient;

    @Override
    public String fileUpload(MultipartFile file) {
        // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
        try {
            //获取当天日期
            String date = DateUtil.formatDate(new Date());
            //文件名
            String fileName = date + "/" + UUID.randomUUID().toString()+"_"+ file.getOriginalFilename();
            //获取文件流
            InputStream stream = file.getInputStream();
            PutObjectOptions option=new PutObjectOptions(file.getSize(),-1L);
            //设置上传头格式
            option.setContentType(file.getContentType());

            // 使用putObject上传一个文件到存储桶中。
            minioClient.putObject("mall-oss",fileName, stream,option);
            String url=minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
